package com.krtech.wecard.utils;

import com.krtech.wecard.module.sys.entity.SysDept;
import com.krtech.wecard.module.sys.pojo.MenuVo;
import com.krtech.wecard.module.sys.pojo.SysDeptVo;

import java.util.ArrayList;
import java.util.List;

public class TreeUtil {

    /**
     * 菜单生成树
     *
     * @param treeList
     * @param pid
     * @return
     */
    public static List<MenuVo> toTree(List<MenuVo> treeList, Long pid) {
        List<MenuVo> retList = new ArrayList<MenuVo>();
        for (MenuVo parent : treeList) {
            if (pid.equals(parent.getPid())) {
                retList.add(findChildren(parent, treeList));
            }
        }
        return retList;
    }

    private static MenuVo findChildren(MenuVo parent, List<MenuVo> treeList) {
        for (MenuVo child : treeList) {
            if (parent.getId().equals(child.getPid())) {
                if (parent.getChildren() == null) {
                    parent.setChildren(new ArrayList<>());
                }
                parent.getChildren().add(findChildren(child, treeList));
            }
        }
        return parent;
    }

    /**
     * 部门生成树
     */
    public static List<SysDeptVo> DepttoTree(List<SysDeptVo> treeList, Long pid) {
        List<SysDeptVo> retList = new ArrayList<SysDeptVo>();
        for (SysDeptVo parent : treeList) {
            if (pid.equals(parent.getPid())) {
                retList.add(DeptfindChildren(parent, treeList));
            }
        }
        return retList;
    }

    private static SysDeptVo DeptfindChildren(SysDeptVo parent, List<SysDeptVo> treeList) {
        for (SysDeptVo child : treeList) {
            Long parentDeptId = parent.getDeptId();
            Long childPid = child.getPid();
            if (parentDeptId.equals(childPid)) {
                if (parent.getChildren() == null) {
                    parent.setChildren(new ArrayList<>());
                }
                parent.getChildren().add(DeptfindChildren(child, treeList));
            }
        }
        return parent;
    }

    public static List<SysDeptVo> DepttoTreeByPcode(List<SysDeptVo> treeList, String pcode) {
        List<SysDeptVo> retList = new ArrayList<SysDeptVo>();
        for (SysDeptVo parent : treeList) {
            if (pcode.equals(parent.getPcode())) {
                retList.add(DeptfindChildrenByPcode(parent, treeList));
            }
        }
        return retList;
    }


    private static SysDeptVo DeptfindChildrenByPcode(SysDeptVo parent, List<SysDeptVo> treeList) {
        for (SysDeptVo child : treeList) {
            String code = parent.getCode();
            String pcode = child.getPcode();
            if (code.equals(pcode)) {
                if (parent.getChildren() == null) {
                    parent.setChildren(new ArrayList<>());
                }
                parent.getChildren().add(DeptfindChildrenByPcode(child, treeList));
            }
        }
        return parent;
    }


}